/**
 * SSP for APP
 * Copyright 2013 Baidu Inc. All rights reserved.
 *
 * @class Navbar
 * @extends esui.Control
 * @file 顶部导航栏
 * @author maoquan
 */

define(
    function (require) {
        var u = require('underscore');
        var lib = require('esui/lib');
        var esui = require('esui');
        var Control = require('esui/Control');
        var etpl = require('etpl');
        var eoo = require('eoo');
        var painters = require('esui/painters');
        var $ = require('jquery');

        var Navbar = eoo.create(
            Control,
            {
                type: 'NavbarList',

                listTemplate: ''
                    + '<!-- for: ${datasource} as ${item} -->'
                    + '    <li><a href="${item.url}" ${item.target}>${item.text}<\/a><\/li>'
                    + '<!-- \/for -->',

                initOptions: function (options) {
                    var properties = {
                        datasource: [],
                        activeItem: ''
                    };
                    u.extend(properties, options);
                    this.setProperties(properties);
                    this.complier = etpl.compile(this.listTemplate);
                },

                initStructure: function (options) {
                    var $main = $(this.main);
                    $main.addClass(this.helper.getPrefixClass('navbar-nav'));
                },

                repaint: painters.createRepaint(
                    Control.prototype.repaint,
                    {
                        name: 'datasource',
                        paint: function (navbar, datasource) {
                            var data = prepareData.call(this, datasource);
                            navbar.main.innerHTML
                                = navbar.complier(
                                    {
                                        datasource: data,
                                        ctrlClassPrefix: navbar.helper.getPrimaryClassName()
                                    }
                                );
                        }
                    }
                )
            }
        );

        function prepareData(datasource) {
            var items = [];
            u.each(
                datasource,
                function (data) {
                    var escapedID = data.id;
                    var openTarget = data.target;
                    if (openTarget) {
                        openTarget = 'target="' + openTarget + '"';
                    }
                    var item = {
                        id: escapedID,
                        text: data.text,
                        url: data.url,
                        target: openTarget
                    };
                    items.push(item);
                },
                this
            );

            return items;
        }

        esui.register(Navbar);
        return Navbar;
    }
);
